#pragma once
#include <cstdio>
#include <sys/types.h>
#include <unistd.h>
#include <stdarg.h>
#include <string>
#include <iostream>
#define NORMAL 1
#define WARING 2
#define ERROR 3
#define FATAL 4
#define LOG_PATH "./log"
using namespace std;
string getTime()
{
    time_t t;
    time(&t);
    struct tm *tmp = localtime(&t);
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "%d-%d-%d %d:%d:%d", tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
    return buffer;
}

const char* getString(int leval)
{
    switch(leval)
    {
        case NORMAL: return "NORMAL";
        case WARING: return "WARING";
        case ERROR: return "ERROR";
        case FATAL: return "FATAL";
        default:return nullptr;
    }
}
void logMessage(int leval,const char* format, ...)
{
    //[日志等级][时间][pid][信息]
    #define NUM 1024
    //日志信息前面的部分
    char logfix[NUM];
    const char* logtime = getTime().c_str();
    snprintf(logfix,sizeof logfix,"[%s][%s][pid:%d]",getString(leval),logtime,getpid());
    char logcontent[NUM];
    va_list arg;
    va_start(arg,format);
    vsnprintf(logcontent,sizeof logcontent,format,arg);
    FILE* fd = fopen(LOG_PATH,"a");
    if(fd == NULL)
    {
        cout<<"log fopen error"<<endl;
        return;
    }
    fprintf(fd,"%s%s\n",logfix,logcontent);
    //fflush(fd);
    fclose(fd);
}